using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Clue_Less_Client.localhost;

namespace Clue_Less_Client
{
    public partial class Login : Form
    {
        localhost.MainService ws;

        private bool thread1complete = false;
        private bool thread2complete = false;
        private bool gamestart = false;
        public int GameID = -1;
        private Player _player;

        public Login()
        {
 
            InitializeComponent();
        }

        public Player ProcessLogin()
        {
            if (ShowDialog() == DialogResult.OK)
                return _player;
            else
                return null;
        }

        private void Login_Load(object sender, EventArgs e)
        {
            try
            {
                ws = new Clue_Less_Client.localhost.MainService();
                loadGames();
            }
            catch (Exception ex) {
                Error.Show("There was an error loading game list. The game server may be down. Please try again later.", ex);
            }
        }

        private void loadGames()
        {
            List<ComboBoxItem> games = new List<ComboBoxItem>();
            games.Add(new localhost.ComboBoxItem());
            games[0].Label = "-";
            games[0].Value = "-";

            ComboBoxItem[] items = null;
            items = ws.GetOpenGames();
            if (items != null)
                games.AddRange(items);
            this.cbGames.DataSource = games;
            this.cbGames.DisplayMember = "Label";
            this.cbGames.ValueMember = "Value";
        }

        #region Drop down control events

        /// <summary>
        /// Handles cbGames SelectedIndexChanged event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbGames_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbGames.SelectedIndex > 0 &&
                ws != null)
            {
                cbCharacters.Enabled =
                    tbUsername.Enabled = true;

                try
                {
                    this.cbCharacters.DataSource = ws.GetAvailableCharacters(int.Parse(((localhost.ComboBoxItem)cbGames.SelectedItem).Value)); ;
                    this.cbCharacters.DisplayMember = "Label";
                    this.cbCharacters.ValueMember = "Value";
                }
                catch (Exception ex)
                {
                    Error.Show("There was an error loading character list. The game server may be down. Please try again later.", ex);
                }
            }
            else
            {
                cbCharacters.Enabled =
                    tbUsername.Enabled = false;
            }
        }

        /// <summary>
        /// Handles cbCharacters SelectedIndexChanged event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbCharacters_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCharacters.SelectedIndex >= 0 &&
                ws != null)
            {
                tbUsername.Enabled = true;
            }
            else
            {
                tbUsername.Enabled = false;
            }
        }

        /// <summary>
        /// Handles tbUsername TextChanged event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbUsername_TextChanged(object sender, EventArgs e)
        {
            if (cbCharacters.SelectedIndex >= 0 &&
                ws != null &&
                tbUsername.Text != null &&
                tbUsername.Text.Length > 0)
            {
                btnLogin.Enabled = true;
            }
            else
            {
                btnLogin.Enabled = false;
            }
        }

        #endregion

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                _player = new Player();
                _player.CharacterType = (Characters)Enum.Parse(typeof(Characters),
                    ((ComboBoxItem)cbCharacters.SelectedItem).Value);
                GameID = int.Parse(((ComboBoxItem)cbGames.SelectedItem).Value);
                _player.PlayerID = ws.LoginPlayer(GameID, (Characters)Enum.Parse(typeof(Characters), ((ComboBoxItem)cbCharacters.SelectedItem).Value), tbUsername.Text);
                _player.PlayerName = tbUsername.Text;
                timer1.Start();
                btnLogin.Enabled = false;
            }
            catch (Exception ex)
            {
                Error.Show("There was an error loading character list. The game server may be down. Please try again later.", ex);
            }
        }

        #region Timer pinging server for game status
        /// <summary>
        /// Timer ticker
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!gamestart)
            {
                thread1complete = false;
                thread2complete = false;

                ws.GetGameStatusAsync(int.Parse(((ComboBoxItem)cbGames.SelectedItem).Value), Guid.NewGuid());
                ws.GetGameStatusCompleted += new GetGameStatusCompletedEventHandler(ws_GetGameStatusCompleted);

                ws.GetCharactersWaitingAsync(int.Parse(((ComboBoxItem)cbGames.SelectedItem).Value), Guid.NewGuid());
                ws.GetCharactersWaitingCompleted += new GetCharactersWaitingCompletedEventHandler(ws_GetCharactersWaitingCompleted);
            }
            else
            {
                if (thread1complete && thread2complete)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }            
        }

        /// <summary>
        /// Async functions called by web service. Returns Characters waiting.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ws_GetCharactersWaitingCompleted(object sender, GetCharactersWaitingCompletedEventArgs e)
        {
            ComboBoxItem[] charNames = null;

            try
            {
                charNames = e.Result;

                if (charNames != null)
                {
                    for (int i = 0; i < charNames.Length; i++)
                    {
                        Characters ch = (Characters)Enum.Parse(typeof(Characters), charNames[i].Value);
                        switch (i + 1)
                        {
                            case 1:
                                this.pictureBox1.Image = Images.characterCards[ch];
                                this.toolTip1.SetToolTip(this.pictureBox1, charNames[i].Label);
                                break;
                            case 2:
                                this.pictureBox2.Image = Images.characterCards[ch];
                                this.toolTip1.SetToolTip(this.pictureBox2, charNames[i].Label);
                                break;
                            case 3:
                                this.pictureBox3.Image = Images.characterCards[ch];
                                this.toolTip1.SetToolTip(this.pictureBox3, charNames[i].Label);
                                break;
                            case 4:
                                this.pictureBox4.Image = Images.characterCards[ch];
                                this.toolTip1.SetToolTip(this.pictureBox4, charNames[i].Label);
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error.Show(ex.Message, ex);
            }

            thread1complete = true;
        }

        /// <summary>
        /// Async functions called by web service. Returns Game status.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ws_GetGameStatusCompleted(object sender, GetGameStatusCompletedEventArgs e)
        {
            try
            {
                if (e.Result == GameStatus.Waiting)
                {
                    tsStatus.Text = "Waiting for other players to join.";
                }
                else
                {
                    gamestart = true;
                }
            }
            catch (Exception ex)
            {
                Error.Show(ex.Message, ex);
            }

            thread2complete = true;
        }

        #endregion

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnNewGame_Click(object sender, EventArgs e)
        {
            NewGame frm = new NewGame();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                loadGames();
                int gameID = frm.GameID;
                foreach (ComboBoxItem item in cbGames.Items)
                {
                    if (item.Value == gameID.ToString())
                        cbGames.SelectedItem = item;
                }
            }
        }
    }
}